import { defineStore } from 'pinia'
import router from '@/router'
import { useRequest } from "@usehook"
import { setRandomKey, pbDecrypt } from "@/utils/tools"

const modules = import.meta.glob('../views/**/*.vue')

const parseRoute = (routes) => {
    if (routes === null || routes === undefined || routes === "undefined") {
        return []
    }
    return routes.map((item) => {
        return {
            path: item.url.startsWith("/") ? item.url : "/" + item.url,
            name: item.name + (item.parentId ? "@" + item.parentId : ""),
            meta: {
                title: item.name,
                icon: item.icon,
                onCache: item.keepAlive === 1,
                onTag: item.onTag === 1,
                parentId: item.parentId ? "@" + item.parentId : ""
            },
            component: modules[`../${item.endpoint.startsWith('/') ? item.endpoint.replace('/', '') : item.endpoint}.vue`]
        }
    });
}

const useUserStore = defineStore("userInfo", {
    state: () => ({
        token: "",
        username: "",
        role: "",
        sequence: "",
        menu: [],
        router: [],
        permission: {},
        avatar: ""
    }),
    getters: {
        getUserInfo: state => ({
            token: state.token ? pbDecrypt(state.token) : "",
            username: state.username ? pbDecrypt(state.username) : "",
            role: state.role ? pbDecrypt(state.role) : "",
            sequence: state.sequence ? pbDecrypt(state.sequence) : "",
            avatar: state.avatar
        }),
        getRouteInfo: state => ({
            menu: state.menu,
            permission: state.permission,
            router: state.router
        }),
        islogin: state => state.token ? true : false,
    },
    actions: {
        login(info) {
            // 确保info对象具有期望的属性
            if (!info || typeof info !== 'object' || !info.token || !info.username || !info.role || !info.sequence) {
                return
            }
            setRandomKey()

            this.$patch((state) => {
                const { token, username, role, sequence } = info;
                state.token = token;
                state.username = username;
                state.role = role;
                state.sequence = sequence;
                this.getUserRouteInfo()
            })
        },
        async getUserRouteInfo() {
            let success = true
            await this.getRolePermission().then((permission) => {
                if (permission) {
                    this.permission = permission
                }
            }).catch(() => success = false)

            await this.getMenuRoute().then((resp) => {
                this.menu = resp.menu
                this.router = resp.router
                this.loadRoute()
            }).catch(() => {
                success = false
                this.menu = ["-"]
                this.router = ["-"]
            })
            return success
        },
        getMenuRoute() {
            return new Promise((resolve, reject) => {
                useRequest({ url: "/menu/getMenu", repeatDelay: 1000 }).then(resp => {
                    if (resp && resp.status) {
                        resolve(resp.data)
                    } else {
                        reject()
                    }
                })
            })
        },
        getRolePermission() {
            return new Promise((resolve, reject) => {
                useRequest({ url: "/user/role/permission", repeatDelay: 1000 }).then(resp => {
                    if (resp && resp.status) {
                        resolve(resp.data)
                    } else {
                        reject()
                    }
                })
            })
        },
        loadRoute() {
            if (this.router.length > 0) {
                for (let route of parseRoute(this.router)) {
                    if (!router.hasRoute(route.name) && route.path) {
                        router.addRoute(route)
                    }
                }
                router.replace(router.options.history.location)
            }
        },
        logout() {
            this.$patch((state) => {
                router.replace("/")
                if (state.token) {
                    // 更新状态
                    useRequest({ url: "/logout", method: "post", token: pbDecrypt(state.token) }).then(res => {
                        console.log(res)
                    }).catch(() => { })
                }
                state.token = ""
                state.username = ""
                state.role = ""
                state.sequence = ""
                state.permission = {}
                for (let route of (state.router || [])) {
                    if (router.hasRoute(route.name) && route.url) {
                        router.removeRoute(route.name)
                    }
                }
                state.menu = []
                state.router = []
            })
        },
        updateUserAvatar(avatar) {
            this.avatar = avatar
        }
    },
    persist: {
        enabled: true,
        key: "userInfo",
        paths: ["role", "sequence", "username", "token"],
        storage: localStorage
    }
})

export default useUserStore